#!/bin/sh
#
#   http://code.google.com/media-translate/
#   Copyright (C) 2010  Serge A. Timchenko
#
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program. If not, see <http://www.gnu.org/licenses/>.
#

# Title: artist_title - track_title
# Size: small|smallsquare|medium|mediumsquare|large|largesquare|mega|original

local DATAPATH=$BASEPATH/app/lastfm
cd $DATAPATH

local LASTFMFILE=$TMPFILE.lastfm

get_opt "Title"
local tracktitle="$opt"

local artist=`expr "$tracktitle" : '\(.*\) - .*' \| ""`
[ -z "$artist" ] && artist=`expr "$tracktitle" : '\([^-]*\)-.*' \| "$tracktitle" | sed 's/ /+/g'`
local track=`expr "$tracktitle" : '.* - \(.*\)' \| ""`
[ -z "$track" ] && track=`expr "$tracktitle" : '.*-\([^-]*\)$' \| "_" | sed 's/ /+/g'` 
local request="http://www.last.fm/music/$artist/_/$track"

get_opt "Size"
local size=largesquare
case $opt in
  small|smallsquare|medium|mediumsquare|large|largesquare|mega|original)
    size=$opt
    ;;
esac

get_opt "Clear-cache"
local clear=
case $opt in
    0|no|No|NO)
        clear=
    ;;
    1|yes|Yes|YES)
        clear=1
    ;;
esac

$MSDL -q -o "$LASTFMFILE" -p http --useragent "$USERAGENT" "$request"

local type=

if [ -f "$LASTFMFILE" ]; then

#  [ -n "$clear" ] && rm -f /tmp/cached/*_trackimage.png 2>&1 > /dev/null
  
  local imageurl=`grep LFM.set\(\"Par "$LASTFMFILE" | sed "s/.*image\":{//;s/},.*//;s/.*\"$size\":\"//;s/\".*//;" | sed 's/\\\//g'`
  rm -f "$LASTFMFILE"
  local buf=`$MSDL --debug -o "$LASTFMFILE" -p http --useragent "$USERAGENT" "$imageurl" 2>&1`
  if [ -f "$LASTFMFILE" ]; then
    type=`echo "$buf" | sed -n '/^[cC]ontent[ -][tT]ype/p' | sed -n '$p' | /usr/local/etc/awk '{ match($0, /[ ;:]+([a-z]+\/[a-z\-]+)[ ;]*.*$/, arr); print arr[1]}'`
  else
    type="image/png"
    cp "empty.png" "$LASTFMFILE"
  fi
else
  type="image/png"
  cp "empty.png" "$LASTFMFILE"
fi

printContent "$type" "$LASTFMFILE"



